package com.haynes.meetxiaohai.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haynes.meetxiaohai.common.CustomException;
import com.haynes.meetxiaohai.common.R;
import com.haynes.meetxiaohai.dto.SetmealDto;
import com.haynes.meetxiaohai.entity.Category;
import com.haynes.meetxiaohai.entity.Setmeal;
import com.haynes.meetxiaohai.service.CategoryService;
import com.haynes.meetxiaohai.service.SetmealDishService;
import com.haynes.meetxiaohai.service.SetmealService;
import com.haynes.meetxiaohai.common.R;
import com.haynes.meetxiaohai.dto.SetmealDto;
import com.haynes.meetxiaohai.entity.Category;
import com.haynes.meetxiaohai.entity.Setmeal;
import com.haynes.meetxiaohai.service.CategoryService;
import com.haynes.meetxiaohai.service.SetmealDishService;
import com.haynes.meetxiaohai.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author Haynes
 * @Date 2023/3/22 14:54
 * @PackageName:com.haynes.reggie.controller
 * @ClassName: SetmealDishController
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisCacheManager redisCacheManager;
    //    套餐信息key前缀
    private static final String SetmealKeyPrefix = "Setmeal_cache";

    @PostMapping
    @CacheEvict(value = SetmealKeyPrefix,allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        setmealService.saveWitchDish(setmealDto);
        return R.success("新增套餐信息成功!");
    }

    /**
     * 主页分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<SetmealDto>> page(int page, int pageSize, String name) {
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);

        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getIsDeleted, 0);
        setmealLambdaQueryWrapper.like(name != null, Setmeal::getName, name);
        setmealLambdaQueryWrapper.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(setmealPage, setmealLambdaQueryWrapper);

        Page<SetmealDto> setmealDtoPage = new Page<>();
//        拷贝setmealPage类的属性除了records
        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");
//        获取套餐分页对象里的所有数据
        List<Setmeal> records = setmealPage.getRecords();

        List<SetmealDto> setmealDtoList = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
//            通过流获取到所有的套餐数据，复制属性到setmealDto中
            BeanUtils.copyProperties(item, setmealDto);

//            通过查询到套餐数据，拿分类ID到分类表中查询数据
            Category category = categoryService.getById(item.getCategoryId());
            if (category != null) {
//                获取到分类名称并赋值给SetmealDto中
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
//              结果返回
            return setmealDto;
        }).collect(Collectors.toList());
//      设置处理过后的套餐数据，并向前端返回
        setmealDtoPage.setRecords(setmealDtoList);
        return R.success(setmealDtoPage);
    }

    @GetMapping("/{id}")
    @CacheEvict(value = SetmealKeyPrefix, key = "#id")
    public R<SetmealDto> getSetmeal(@PathVariable Long id) {
        SetmealDto setmealDto = setmealService.getByIdWitchDish(id);
        return R.success(setmealDto);
    }

    @PutMapping
    @CacheEvict(value = SetmealKeyPrefix,key = "#dto.categoryId")
    public R<String> update(@RequestBody SetmealDto dto) {
        setmealService.updateWitchDish(dto);
        return R.success("更新菜品信息成功!");
    }

    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable Integer status, @RequestParam List<Long> ids) {
        setmealService.updateSetmealStatusByIdBatch(status,ids);
        return R.success("更新套餐状态成功");
    }

    @DeleteMapping
    @CacheEvict(value = SetmealKeyPrefix,allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids) {
        setmealService.removeByIdBatch(ids);
        return R.success("删除套餐信息成功!");
    }

    /**
     * 根据分类ID查询套餐
     * unless：不满足某一条件加入缓存中
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = SetmealKeyPrefix, key = " #setmeal.categoryId ",unless = "#result == null ")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        LambdaQueryWrapper<Setmeal> dishWrapper = new LambdaQueryWrapper<>();
        dishWrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        dishWrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, 1);
        dishWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> dishList = setmealService.list(dishWrapper);
        return R.success(dishList);
    }

}

